package com.tutu.borrow.service.impl;

import com.tutu.borrow.entity.Borrow;
import com.tutu.borrow.mapper.BorrowMapper;
import com.tutu.borrow.service.BorrowService;
import com.tutu.commons.feign.BookClient;
import com.tutu.commons.feign.UserClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @Program: SpringCloud
 * @Description:
 * @Author: JK.TuTu
 * @Version: 1.0
 * @Create: 2022-12-01 14:19
 **/
@Service
public class BorrowServiceImpl implements BorrowService {

    @Resource
    BorrowMapper mapper;

    @Resource
    private UserClient userClient;


    @Resource
    private BookClient bookClient;


    /**
     * 通过id查询出借阅信息
     *
     * @param id borrow表id
     * @return
     */
    @Override
    public Borrow getBorrowInfo(int id) {
        Borrow borrowInfo = mapper.getBorrowInfo(id);
        return borrowInfo;
    }


    /**
     * 根据uid和bid查询图书信息
     */
    @Override
    public Borrow getBorrow(int uid, int bid) {
        return mapper.getBorrow(uid, bid);
    }

    /**
     * 添加图书借阅信息
     *
     * @param uid 用户id
     * @param bid 图书id
     * @return
     */
    @Override
    public int addBorrowInfo(int uid, int bid) {
        return mapper.addBorrowInfo(uid,bid);
    }

    /**
     * 实现图书借阅
     */
    @Override
    public boolean doBorrow(int uid, int bid) {
        //1.判断图书和用户是否都支持借阅
        if (bookClient.getBookNum(bid) < 1) throw new RuntimeException("图书数量不足！");
        if (userClient.getUserNum(uid) < 1) throw new RuntimeException("用户借阅量已经超过3本");
        //2.判断该图书是否已经被该用户已借阅
        Borrow borrow = getBorrow(uid, bid);
        if (borrow !=null) throw new RuntimeException("该图书已经被该用户借阅！");
        //3.进行book表,user表,borrow表的修改
        bookClient.bookBorrow(bid);
        userClient.userBorrow(uid);
        addBorrowInfo(uid,bid);
        return true;
    }
}
